package com.linzt.candy.wxmp.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.linzt.candy.common.core.utils.bean.BeanUtils;
import com.linzt.candy.wxmp.domain.WxMpUser;
import com.linzt.candy.wxmp.mapper.WxMpUserMapper;
import com.linzt.candy.wxmp.service.IWxMpUserService;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.WxMpUserQuery;
import me.chanjar.weixin.mp.bean.result.WxMpUserList;
import org.apache.commons.lang3.ObjectUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

import static me.chanjar.weixin.mp.enums.WxMpApiUrl.User.USER_GET_URL;
import static me.chanjar.weixin.mp.enums.WxMpApiUrl.User.USER_INFO_BATCH_GET_URL;

/**
 * @Author linzt
 * @Date 2020/12/207:26 下午
 * @Description 微信公众号关注用户服务类
 * @Version 1.0
 */
@Service
public class WxMpUserServiceImpl extends ServiceImpl<WxMpUserMapper, WxMpUser> implements IWxMpUserService {

    private static final Logger logger = LoggerFactory.getLogger(WxMpUserServiceImpl.class);
    @Resource
    private WxMpUserMapper wxMpUserMapper;
    @Autowired
    private WxMpService wxMpService;

    @Override
    public boolean insert(WxMpUser wxMpUser) {
        boolean flag = false;
        int count = wxMpUserMapper.insert(wxMpUser);
        if (count > 0) {
            flag = true;
        }
        return flag;
    }

    @Override
    public boolean update(WxMpUser wxMpUser) {
        boolean flag = false;
        int count = wxMpUserMapper.updateById(wxMpUser);
        if (count > 0) {
            flag = true;
        }
        return flag;
    }

    @Override
    public WxMpUser findById(WxMpUser wxMpUser) {
        return wxMpUserMapper.selectById(wxMpUser.getId());
    }

    @Override
    public List<WxMpUser> findList(WxMpUser wxMpUser) {
        QueryWrapper<WxMpUser> wrapper = new QueryWrapper<>();
        wrapper.setEntity(wxMpUser);
        return wxMpUserMapper.selectList(wrapper);
    }

    @Override
    public void deleteAll(String[] ids) {
        for (String id : ids) {
            wxMpUserMapper.deleteById(id);
        }
    }

    @Override
    public void sync() throws WxErrorException {
        String nextOpenid = null;
        // 获取关注用户openid列表
        String responseContent = wxMpService.get(USER_GET_URL, nextOpenid == null ? null : "next_openid=" + nextOpenid);
        WxMpUserList wxMpUserList = WxMpUserList.fromJson(responseContent);
        // 一次获取100条用户信息,遍历步长100
        for (int i = 0; i < wxMpUserList.getCount(); i += 100) {
            // 截取长度100的子串
            int len = 100;
            // 数量不够，截取余下的
            if (wxMpUserList.getCount() - i < 100) {
                len = wxMpUserList.getCount() - i;
            }
            responseContent = wxMpService.post(USER_INFO_BATCH_GET_URL, new WxMpUserQuery(wxMpUserList.getOpenids().subList(i, i + len)).toJsonString());
            // 封装返回的信息
            me.chanjar.weixin.mp.bean.result.WxMpUser.fromJsonList(responseContent).stream().map(item -> {
                WxMpUser wxMpUser = new WxMpUser();
                wxMpUser.setOpenid(item.getOpenId());
                wxMpUser.setSubscribe(item.getSubscribe());
                wxMpUser.setNickname(item.getNickname());
                wxMpUser.setSex(item.getSex());
                wxMpUser.setLanguage(item.getLanguage());
                wxMpUser.setCity(item.getCity());
                wxMpUser.setProvince(item.getProvince());
                wxMpUser.setCountry(item.getCountry());
                wxMpUser.setHeadimgurl(item.getHeadImgUrl());
                wxMpUser.setSubscribeTime(item.getSubscribeTime());
                wxMpUser.setUnionid(item.getUnionId());
                wxMpUser.setRemark(item.getRemark());
                wxMpUser.setGroupid(item.getGroupId());
                wxMpUser.setTagidList(Arrays.stream(item.getTagIds()).map(String::valueOf).collect(Collectors.joining(",")));
                wxMpUser.setSubscribeScene(item.getSubscribeScene());
                wxMpUser.setQrScene(item.getQrScene());
                wxMpUser.setQrSceneStr(item.getQrSceneStr());
                WxMpUser oldWxMpUser = this.wxMpUserMapper.findByOpenid(wxMpUser.getOpenid());
                /**
                 * 当前关注用户不存在
                 */
                if (ObjectUtils.isEmpty(oldWxMpUser)) {
                    wxMpUserMapper.insert(wxMpUser);
                } else {
                    BeanUtils.copyBeanProp(oldWxMpUser, wxMpUser);
                    wxMpUserMapper.updateById(oldWxMpUser);
                }
                return oldWxMpUser;
            });
        }
        logger.info("下一个：{}", wxMpUserList.getNextOpenid());
    }

    @Override
    public IPage<WxMpUser> selectByPage(WxMpUser wxMpUser, int pageIndex, int pageSize) {
        Page<WxMpUser> page = new Page<>();
        page.setCurrent(pageIndex).setSize(pageSize);
        QueryWrapper<WxMpUser> wrapper = new QueryWrapper<>();
        wrapper.setEntity(wxMpUser);
        return this.wxMpUserMapper.selectPage(page, wrapper);
    }

}
